package com.cwnu.controller;

import com.cwnu.entity.User;
import com.cwnu.result.R;
import com.cwnu.service.UserService;
import com.cwnu.utils.JWTUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Objects;

/**
 * @ProjectName: mall-cwnu
 * @Titile: UserController
 * @Author: Lucky
 * @Description: 用户控制类
 */
@RestController //类中所有的控制方法都要返回json数据
@RequestMapping("user") //一级路由
@Slf4j //添加日志
@Api("用户模块")
public class UserController {
    @Autowired //ioc
    private UserService userService;


    /**
     * 登录控制
     * @param userName
     * @param userPassword
     * @return
     */
    @PostMapping("login")
    @ApiOperation(value = "用户登录接口",notes = "用户名和密码不为空")
    @ApiImplicitParams({
            @ApiImplicitParam(value = "用户名",name = "userName",required = true,dataType = "String",paramType = "query"),
            @ApiImplicitParam(value = "密码",name = "userPassword",required = true,dataType = "String",paramType = "query")
    })
    public Object login(String userName,String userPassword){
        log.info("登录的信息：{},{}",userName,userPassword);
        if(Objects.isNull(userName) || Objects.isNull(userPassword)){
            throw  new RuntimeException("用户名或密码不能为空");
        }
        //调用service层进行业务逻辑处理
        User user = userService.login(userName, userPassword);
        if(Objects.isNull(user)){
            throw new RuntimeException("用户名或密码错误");
        }
        log.info("登录成功的用户信息：{}",user);
        //  token的生成
        String token = JWTUtil.generateToken(user);
        //返回的数据怎么处理
        return R.ok().data("userNickName",user.getUserNickName()).data("token",token);

    }

}
